package com.beauty.controller;

import com.beauty.dto.BeautyResponse;
import com.beauty.dto.login.LoginData;
import com.beauty.dto.login.RegisterData;
import com.beauty.dto.note.User;
import com.beauty.mapper.IUserMapper;
import com.beauty.services.MyBaitsHelp;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/api/login")
public class LoginController {
    LoginController(MyBaitsHelp myBaitsHelp) {
        this.myBaitsHelp = myBaitsHelp;
    }

    private final MyBaitsHelp myBaitsHelp;

    /**
     * 登录
     *
     * @param data
     * @param response
     * @return
     */
    @PostMapping("/signIn")
    public BeautyResponse<User> login(@RequestBody() LoginData data, HttpServletResponse response) {
        var res = new BeautyResponse<User>();
        res.response = new User();
        // 开始操作数据库
        try (var session = this.myBaitsHelp.factory.openSession()) {
            var user = session.getMapper(IUserMapper.class).selectUserByUserName(data.username);
            if (user == null) {
                res.status = HttpStatus.INTERNAL_SERVER_ERROR.value();
                res.message = "没有这个用户";
                return res;
            }
            if (user.password.equals(data.password)) {
                var cookie = new Cookie("userId", user.id);
                cookie.setPath("/");
                response.addCookie(cookie);
                res.response.avatar = user.avatar;
                res.response.name = user.name;
                res.response.id = user.id;
                res.message = "成功";
                return res;
            }
            res.status = HttpStatus.INTERNAL_SERVER_ERROR.value();
            res.message = "密码错误";
            return res;
        } catch (Error e) {
            res.message = e.getMessage();
            return res;
        }
    }


    /**
     * 注册
     *
     * @param register
     * @return
     */
    @PostMapping("/register")
    public BeautyResponse<String> register(@RequestBody() RegisterData register) {
        var res = new BeautyResponse<String>();
        // 开始操作数据库
        try (var session = this.myBaitsHelp.factory.openSession()) {
            session.getMapper(IUserMapper.class).InsertUser(UUID.randomUUID().toString(), register.username, register.password, "");
            res.message = "成功";
            return res;
        } catch (Error error) {
            throw error;
        }
    }
}
